package leetCode.firstWeek;

import java.util.Arrays;
import java.util.Stack;

public class Code_67 {
  public String addBinary(String a, String b) {
    Stack<Integer> result = new Stack<>();
    a = "0" + a;
    b = "0" + b;
    int aP = a.length() - 1;
    int bP = b.length() - 1;
    int carry = 0;

    while (aP > -1 | bP > -1) {
      if (aP == -1) {
        int tmpB = Integer.parseInt(String.valueOf(b.charAt(bP)));
        if (tmpB + carry >= 2) {
          result.push(tmpB + carry - 2);
          carry = 1;
        } else {
          result.push(tmpB + carry);
          carry = 0;
        }
        bP--;
        continue;
      }
      if (bP == -1) {
        int tmpA = Integer.parseInt(String.valueOf(a.charAt(aP)));
        if (tmpA + carry == 2) {
          result.push(0);
          carry = 1;
        } else {
          result.push(tmpA + carry);
          carry = 0;
        }
        aP--;
        continue;
      }
      int tmpB = Integer.parseInt(String.valueOf(b.charAt(bP)));
      int tmpA = Integer.parseInt(String.valueOf(a.charAt(aP)));
      if (tmpA + tmpB + carry >= 2) {
        result.push(tmpA + tmpB + carry - 2);
        carry = 1;
        aP--;
        bP--;
        continue;
      }
      result.push(tmpA + tmpB + carry);
      carry = 0;
      aP--;
      bP--;
    }

    String tmp = "";
    int tmpRes = result.size();

    for (int i = 0; i < tmpRes; i++) {
      if (i == 0 && result.peek() == 0) {
        result.pop();
        continue;
      }
      tmp += result.pop();
    }

    return tmp;
  }
}
